package by.yakusekmaxim.bookgid.services.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.metamodel.SingularAttribute;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import by.yakusekmaxim.bookgid.dataaccess.AuthorDao;
import by.yakusekmaxim.bookgid.dataaccess.BookDao;
import by.yakusekmaxim.bookgid.dataaccess.util.Filter;
import by.yakusekmaxim.bookgid.datamodel.Author;
import by.yakusekmaxim.bookgid.datamodel.Book;
import by.yakusekmaxim.bookgid.datamodel.Book_;
import by.yakusekmaxim.bookgid.services.AuthorService;

@Service
public class AuthorServiceImpl implements AuthorService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(AuthorServiceImpl.class);

	@Inject
	private AuthorDao dao;

	@Inject
	private BookDao daoBook;

	@Override
	public Author get(Long id) {
		Author entity = dao.getById(id);
		return entity;
	}

	@Override
	public void saveOrUpdate(Author author) {
		if (author.getId() == null) {
			LOGGER.debug("Save new: {}", author);
			dao.insert(author);
		} else {
			LOGGER.debug("Update: {}", author);
			dao.update(author);
		}
	}

	@Override
	public void delete(Author author) {
		List<Book> bookList = daoBook.getAllBooks(Book_.author,author);
		if (bookList != null) {
			for (Book book : bookList) {
				book.setAuthor(null);
				LOGGER.debug("Update: {}", book);
				daoBook.update(book);
			}
		}
		LOGGER.debug("Remove: {}", author);
		dao.delete(author.getId());
	}

	@Override
	public void deleteAll() {
		LOGGER.debug("Remove all images");
		dao.deleteAll();
	}

	@Override
	public List<Author> getAllAuthor(SingularAttribute<Author, ?> attr,
			boolean ascending, int startRecord, int pageSize) {
		return dao.getAllAuthor(attr, ascending, startRecord, pageSize);
	}

	@Override
	public List<Author> getAllAuthor(SingularAttribute<Author, ?> attr,
			boolean ascending, int startRecord, int pageSize,
			Filter<Author> filter) {
		return dao.getAllAuthor(attr, ascending, startRecord, pageSize, filter);
	}

	@Override
	public Long getCount() {
		return dao.getCount();
	}

	@Override
	public Long getCount(SingularAttribute<Author, ?> attribute, Object value) {
		return dao.getCount(attribute, value);
	}

	@Override
	public List<Author> getAll() {
		LOGGER.debug("Get all Author");
		return dao.getAll();
	}

}
